package com.shopx.cm.service.impl;


import com.alibaba.fastjson.JSON;
import com.shopx.auth.bean.SysOrg;
import com.shopx.auth.dao.db1.SysOrgDao;
import com.shopx.auth.model.SysOrgModel;
import com.shopx.auth.service.impl.BaseAuthService;
import com.shopx.base.constants.ResultCodeEnum;
import com.shopx.base.exception.OriginException;
import com.shopx.base.exception.ShopxException;
import com.shopx.base.service.ISysSeqService;
import com.shopx.cm.bean.CmMaterial;
import com.shopx.cm.bean.CmMeasure;
import com.shopx.cm.bean.CmSend;
import com.shopx.cm.bean.CmSendRemark;
import com.shopx.cm.dao.db1.CmMaterialDao;
import com.shopx.cm.dao.db1.CmSendDao;
import com.shopx.cm.dao.db1.CmSendRemarkDao;
import com.shopx.cm.dao.db2.SendDao;
import com.shopx.cm.dto.*;
import com.shopx.cm.model.CmMaterialModel;
import com.shopx.cm.model.CmSendModel;
import com.shopx.cm.service.ICmSendService;
import com.shopx.cmm.DTO.PageDTO;
import com.shopx.core.utils.DateTimeUtil;
import com.shopx.core.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * TODO
 *
 * @author lituo
 * @className: CmSend
 * @date 2025-01-07
 */
@Service
@Slf4j
public class CmSendServiceImpl extends BaseAuthService implements ICmSendService {

    @Resource
    private CmSendDao cmSendDao;

    @Resource
    private CmMaterialDao cmMaterialDao;

    @Resource
    private CmSendRemarkDao cmSendRemarkDao;

    @Resource
    private SendDao sendDao;

    @Resource
    private SysOrgDao sysOrgDao;

    @Resource
    private ISysSeqService sysSeqService;

    @Value("${sync.days}")
    private String syncDays;

    @Override
    public CmSendModel selectByPrimaryKey(CmSend cmSend) {
        if (cmSend == null) {
            throw new ShopxException(ResultCodeEnum.PAR_NULL);
        }
        return cmSendDao.selectByPrimaryKey(cmSend);
    }

    @Override
    @Transactional(value = "db1", rollbackFor = Exception.class)
    public int insertSelective(CmSend cmSend) {
        if (cmSend == null) {
            throw new ShopxException(ResultCodeEnum.PAR_NULL);
        }
        int result = cmSendDao.insertSelective(cmSend);
        if (result != 1) {
            throw new ShopxException(ResultCodeEnum.DB_ERROR);
        }
        return result;
    }

    @Override
    @Transactional(value = "db1", rollbackFor = Exception.class)
    public int updateByPrimaryKeySelective(CmSendModel cmSend) {
        if (cmSend == null) {
            throw new ShopxException(ResultCodeEnum.PAR_NULL);
        }
        int result = 0;
        if(!StringUtil.isEmpty(cmSend.getSendRemark())){
            //查询记录
            CmSend cs = new CmSend();
            cs.setCmsId(cmSend.getCmsId());
            CmSendModel record = cmSendDao.selectByPrimaryKey(cs);
            if(record==null){
                throw new OriginException("记录不存在");
            }
            //验证权限
            String materialId = record.getMaterialId();
            //查询电话号码
            CmMaterial cmMaterial = new CmMaterial();
            cmMaterial.setUserId(materialId);
            CmMaterialModel cmm= cmMaterialDao.selectByKey(cmMaterial);
            if(cmm==null){
                throw new OriginException("材料员不存在");
            }
            if(!super.getLoginUserInfo().getLoginName().equals(cmm.getUserTel())){
                throw new OriginException("对不起，只有工地绑定的材料员才有权限修改");
            }
            CmSendRemark cmSendRemark = new CmSendRemark();
            cmSendRemark.setCusId(record.getCusId());
            cmSendRemark.setOrgId(record.getOrgId());
            cmSendRemark.setSendRemark(cmSend.getSendRemark());
            result = cmSendRemarkDao.updateByKey(cmSendRemark);
            if (result != 1) {
                throw new ShopxException(ResultCodeEnum.DB_ERROR);
            }
        }else{
            result = cmSendDao.updateByPrimaryKeySelective(cmSend);
            if (result != 1) {
                throw new ShopxException(ResultCodeEnum.DB_ERROR);
            }
        }
        return result;
    }

    @Override
    @Transactional(value = "db1", rollbackFor = Exception.class)
    public int deleteByPrimaryKey(CmSend cmSend) {
        if (cmSend == null) {
            throw new ShopxException(ResultCodeEnum.PAR_NULL);
        }
        int result = cmSendDao.deleteByPrimaryKey(cmSend);
        if (result != 1) {
            throw new ShopxException(ResultCodeEnum.DB_ERROR);
        }
        return result;
    }

    @Override
    public int selectCount(CmSendModel cmSend) {
        return cmSendDao.selectCount(cmSend);
    }

    @Override
    public List<CmSendModel> selectList(CmSendModel cmSend) {
        List<CmSendModel> list = cmSendDao.selectList(cmSend);
        return list;
    }

    @Override
    public PageDTO<CmSendModel> getListPage(CmSendModel cmSend) {
        if (cmSend == null) {
            throw new ShopxException(ResultCodeEnum.PAR_NULL);
        }
        //查询所在部门
//        String userOrgId = super.getUserOrgId();
//        SysOrg sysOrg = new SysOrg();
//        sysOrg.setOrgId(userOrgId);
//        sysOrg.setCpId(super.getUserCpId());
//        SysOrgModel som = sysOrgDao.selectByPrimaryKey(sysOrg);
//        if(som==null){
//            throw new OriginException("获取部门信息失败");
//        }
        String  orgId = cmSend.getOrgId();
        String orgIds[] = super.queryCondOrgIds(orgId);
        cmSend.setOrgIdChk(orgIds);
        PageDTO<CmSendModel> pageDTO = new PageDTO<CmSendModel>();
        pageDTO.setiTotalDisplayRecords(selectCount(cmSend));
        pageDTO.setData(selectList(cmSend));
        return pageDTO;
    }


    /**
     * 同步erp数据
     */
    public void syncErpData(){
        log.info("CmSendService.syncErpDate.begin");
        MeasureReqDTO dto = new MeasureReqDTO();
        //查询当前天数之前一年的数据
        String endDt2 = DateTimeUtil.getDate8();
        String endDt = DateTimeUtil.formatDtm(endDt2+"000000");
        String begDt = DateTimeUtil.dateCalc(endDt2,null,"D",Integer.parseInt(syncDays)*(-1));
        begDt = DateTimeUtil.formatDtm(begDt+"000000");
        dto.setBegDt(begDt);
        dto.setEndDt(endDt);
        List<CmSend> list = sendDao.queryList(dto);
        log.info("list.size:{}，准备同步数据",list.size());
        cmSendDao.truncateTable();
        log.info("清空数据完成");
        //2000条一次同步
        for (int i = 0; i < list.size(); i += 200) {
            List<CmSend> subList = list.subList(i, Math.min(i + 200, list.size()));
            log.info("分批同步开始同步，同步总数：{}",subList.size());
            cmSendDao.insertBatch(subList);
            log.info("分批同步数据完成，同步总数：{}",subList.size());
        }
        log.info("同步全部数据完成");


        //修改延期数据
        List<CmSendModel> csList = cmSendDao.selectList(null);
        //步骤1、查询部门
        SysOrgModel sysOrg = new SysOrgModel();
        List<SysOrgModel> orgList = sysOrgDao.selectList(sysOrg);

        //定义一个新的List

        //绑定大区编号
        Map<String, SysOrgModel> orgMap = orgList.stream()
                .collect(Collectors.toMap(SysOrgModel::getOrgId, bean -> bean, (existing, replacement) -> existing));

        csList.forEach(bean -> {
            SysOrgModel sysOrgModel = orgMap.get(bean.getOrgId());
            if (sysOrgModel != null) {
                bean.setRegionId(sysOrgModel.getParOrgId());
                bean.setCzCfDelayDays(sysOrgModel.getCzCfDelayDays());
                bean.setDbCfDelayDays(sysOrgModel.getDbCfDelayDays());
                bean.setJjCfDelayDays(sysOrgModel.getJjCfDelayDays());
                bean.setCgCfDelayDays(sysOrgModel.getCgCfDelayDays());
                bean.setDzgCfDelayDays(sysOrgModel.getDzgCfDelayDays());
                bean.setDlsCfDelayDays(sysOrgModel.getDlsCfDelayDays());
                bean.setKgCfDelayDays(sysOrgModel.getKgCfDelayDays());
                bean.setDjCfDelayDays(sysOrgModel.getDjCfDelayDays());
                bean.setLhjmCfDelayDays(sysOrgModel.getLhjmCfDelayDays());
                bean.setFmCfDelayDays(sysOrgModel.getFmCfDelayDays());
                bean.setKbCfDelayDays(sysOrgModel.getKbCfDelayDays());
            }
        });


        //延期标记
        for(CmSendModel csm:csList){
            CmSendModel cs = new CmSendModel();
            cs.setCmsId(csm.getCmsId());
            cs.setRegionId(csm.getRegionId());
            cs.setCzCfDelayDays(csm.getCzCfDelayDays());
            cs.setDbCfDelayDays(csm.getDbCfDelayDays());
            cs.setJjCfDelayDays(csm.getJjCfDelayDays());
            cs.setCgCfDelayDays(csm.getCgCfDelayDays());
            cs.setDzgCfDelayDays(csm.getDzgCfDelayDays());
            cs.setDlsCfDelayDays(csm.getDlsCfDelayDays());
            cs.setKgCfDelayDays(csm.getKgCfDelayDays());
            cs.setDjCfDelayDays(csm.getDjCfDelayDays());
            cs.setLhjmCfDelayDays(csm.getLhjmCfDelayDays());
            cs.setFmCfDelayDays(csm.getFmCfDelayDays());
            cs.setKbCfDelayDays(csm.getKbCfDelayDays());
            //瓷砖延期计算
            CmSendDelayDTO czDto = this.calDelay(csm.getCzSendDt(),csm.getCzOrderDt(),csm.getCzCfDelayDays());
            cs.setCzDelayFlag(czDto.getDelayFlag());
            cs.setCzDelayDays(czDto.getDelayDays());
            //地板延期计算
            CmSendDelayDTO dbDto = this.calDelay(csm.getDbInstallDt(),csm.getDbOrderDt(),csm.getDbCfDelayDays());
            cs.setDbDelayFlag(dbDto.getDelayFlag());
            cs.setDbDelayDays(dbDto.getDelayDays());
            //洁具延期计算
            CmSendDelayDTO jjDto = this.calDelay(csm.getJjInstallDt(),csm.getJjOrderDt(),csm.getJjCfDelayDays());
            cs.setJjDelayFlag(jjDto.getDelayFlag());
            cs.setJjDelayDays(jjDto.getDelayDays());
            //橱柜延期计算
            CmSendDelayDTO cgDto = this.calDelay(csm.getCgInstallDt(),csm.getCgOrderDt(),csm.getCgCfDelayDays());
            cs.setCgDelayFlag(cgDto.getDelayFlag());
            cs.setCgDelayDays(cgDto.getDelayDays());
            //定制柜延期计算
            CmSendDelayDTO dzgDto = this.calDelay(csm.getDzgInstallDt(),csm.getDzgOrderDt(),csm.getDzgCfDelayDays());
            cs.setDzgDelayFlag(dzgDto.getDelayFlag());
            cs.setDzgDelayDays(dzgDto.getDelayDays());
            //大理石延期计算
            CmSendDelayDTO dlsDto = this.calDelay(csm.getDlsInstallDt(),csm.getDlsOrderDt(),csm.getDlsCfDelayDays());
            cs.setDlsDelayFlag(dlsDto.getDelayFlag());
            cs.setDlsDelayDays(dlsDto.getDelayDays());
            //开关延期计算
            CmSendDelayDTO kgDto = this.calDelay(csm.getKgSendDt(),csm.getKgOrderDt(),csm.getKgCfDelayDays());
            cs.setKgDelayFlag(kgDto.getDelayFlag());
            cs.setKgDelayDays(kgDto.getDelayDays());
            //灯具延期计算
            CmSendDelayDTO djDto = this.calDelay(csm.getDjInstallDt(),csm.getDjOrderDt(),csm.getDjCfDelayDays());
            cs.setDjDelayFlag(djDto.getDelayFlag());
            cs.setDjDelayDays(djDto.getDelayDays());
            //铝合金门延期计算
            CmSendDelayDTO lhjmDto = this.calDelay(csm.getLhjmInstallDt(),csm.getLhjmOrderDt(),csm.getLhjmCfDelayDays());
            cs.setLhjmDelayFlag(lhjmDto.getDelayFlag());
            cs.setLhjmDelayDays(lhjmDto.getDelayDays());
            //房门延期计算
            CmSendDelayDTO fmDto = this.calDelay(csm.getFmInstallDt(),csm.getFmOrderDt(),csm.getFmCfDelayDays());
            cs.setFmDelayFlag(fmDto.getDelayFlag());
            cs.setFmDelayDays(fmDto.getDelayDays());
            //扣板延期计算
            CmSendDelayDTO kbDto = this.calDelay(csm.getKbInstallDt(),csm.getKbOrderDt(),csm.getKbCfDelayDays());
            cs.setKbDelayFlag(kbDto.getDelayFlag());
            cs.setKbDelayDays(kbDto.getDelayDays());
            try {
                cmSendDao.updateByPrimaryKeySelective(cs);
            }catch (Exception e){
                log.error("cs:{},obj:{},ex:{}", cs.getCmsId(),JSON.toJSONString(cs),e);
                continue;
            }
        }
    }


    private CmSendDelayDTO calDelay(String endDt, String begDt, BigDecimal delayCfDays){
        CmSendDelayDTO dto = new CmSendDelayDTO();
        if(StringUtil.isEmpty(begDt)){
            dto.setDelayFlag("没有延期");
            dto.setDelayDays(new BigDecimal(0));
            return dto;
        }
        if(StringUtil.isEmpty(endDt)){
            endDt = DateTimeUtil.getDateTime14();
        }
        long disDay = DateTimeUtil.getDistanceDay(begDt.substring(0,8),endDt.substring(0,8));
        BigDecimal dd = new BigDecimal(disDay);
        dto.setDelayDays(dd);
        if(dd.compareTo(delayCfDays)>=0){
            dto.setDelayFlag("延期");
        }else{
            dto.setDelayFlag("没有延期");
        }
        return dto;
    }

    @Override
    public List<CmSendStateDTO> selectSendStateRpt(CmSendModel cmSend){
        //瓷砖、地板、洁具、橱柜、定制柜、大理石、开关、灯具、铝合金门、房门、扣板
        if("cz".equals(cmSend.getBrand())){
            //瓷砖
            cmSend.setBrand("cz_supplier");
            cmSend.setOrderDt("cz_order_dt");
            cmSend.setDelayFlag("cz_delay_flag");
        }else if("db".equals(cmSend.getBrand())){
            //地板
            cmSend.setBrand("db_supplier");
            cmSend.setOrderDt("db_order_dt");
            cmSend.setDelayFlag("db_delay_flag");
        }else if("jj".equals(cmSend.getBrand())){
            //洁具
            cmSend.setBrand("jj_supplier");
            cmSend.setOrderDt("jj_order_dt");
            cmSend.setDelayFlag("jj_delay_flag");
        }else if("cg".equals(cmSend.getBrand())){
            //橱柜
            cmSend.setBrand("cg_supplier");
            cmSend.setOrderDt("cg_order_dt");
            cmSend.setDelayFlag("cg_delay_flag");
        }else if("dzg".equals(cmSend.getBrand())){
            //定制柜
            cmSend.setBrand("dzg_supplier");
            cmSend.setOrderDt("dzg_order_dt");
            cmSend.setDelayFlag("dzg_delay_flag");
        }else if("dls".equals(cmSend.getBrand())){
            //大理石
            cmSend.setBrand("dls_supplier");
            cmSend.setOrderDt("dls_order_dt");
            cmSend.setDelayFlag("dls_delay_flag");
        }else if("kg".equals(cmSend.getBrand())){
            //开关
            cmSend.setBrand("kg_supplier");
            cmSend.setOrderDt("kg_order_dt");
            cmSend.setDelayFlag("kg_delay_flag");
        }else if("dj".equals(cmSend.getBrand())){
            //灯具
            cmSend.setBrand("dj_supplier");
            cmSend.setOrderDt("dj_order_dt");
            cmSend.setDelayFlag("dj_delay_flag");
        }else if("lhjm".equals(cmSend.getBrand())){
            //铝合金门
            cmSend.setBrand("lhjm_supplier");
            cmSend.setOrderDt("lhjm_order_dt");
            cmSend.setDelayFlag("lhjm_delay_flag");
        }else if("fm".equals(cmSend.getBrand())){
            //房门
            cmSend.setBrand("fm_supplier");
            cmSend.setOrderDt("fm_order_dt");
            cmSend.setDelayFlag("fm_delay_flag");
        }else if("kb".equals(cmSend.getBrand())){
            //扣板
            cmSend.setBrand("kb_supplier");
            cmSend.setOrderDt("kb_order_dt");
            cmSend.setDelayFlag("kb_delay_flag");
        }else{
            //瓷砖
            cmSend.setBrand("cz_supplier");
            cmSend.setOrderDt("cz_order_dt");
            cmSend.setDelayFlag("cz_delay_flag");
        }

        //查询所在部门
//        String userOrgId = super.getUserOrgId();
//        SysOrg sysOrg = new SysOrg();
//        sysOrg.setOrgId(userOrgId);
//        sysOrg.setCpId(super.getUserCpId());
//        SysOrgModel som = sysOrgDao.selectByPrimaryKey(sysOrg);
//        if(som==null){
//            throw new OriginException("获取部门信息失败");
//        }
        String  orgId = cmSend.getOrgId();
        String orgIds[] = super.queryCondOrgIds(orgId);
        cmSend.setOrgIdChk(orgIds);
        List<CmSendStateDTO> list = cmSendDao.selectSendStateRpt(cmSend);
        return list;
    }


    @Override
    public List<CmStateDTO> selectFinanceStateRpt(CmSendModel cmSend){
        //查询所在部门
//        String userOrgId = super.getUserOrgId();
//        SysOrg sysOrg = new SysOrg();
//        sysOrg.setOrgId(userOrgId);
//        sysOrg.setCpId(super.getUserCpId());
//        SysOrgModel som = sysOrgDao.selectByPrimaryKey(sysOrg);
//        if(som==null){
//            throw new OriginException("获取部门信息失败");
//        }
        String  orgId = cmSend.getOrgId();
        String orgIds[] = super.queryCondOrgIds(orgId);
        cmSend.setOrgIdChk(orgIds);
        List<CmStateDTO> list = cmSendDao.selectFinanceStateRpt(cmSend);
        return list;
    }

    @Override
    public List<CmStateDTO> selectBuildStateRpt(CmSendModel cmSend){
        //查询所在部门
//        String userOrgId = super.getUserOrgId();
//        SysOrg sysOrg = new SysOrg();
//        sysOrg.setOrgId(userOrgId);
//        sysOrg.setCpId(super.getUserCpId());
//        SysOrgModel som = sysOrgDao.selectByPrimaryKey(sysOrg);
//        if(som==null){
//            throw new OriginException("获取部门信息失败");
//        }
        String  orgId = cmSend.getOrgId();
        String orgIds[] = super.queryCondOrgIds(orgId);
        cmSend.setOrgIdChk(orgIds);
        List<CmStateDTO> list = cmSendDao.selectBuildStateRpt(cmSend);
        return list;
    }
}

